<?php

namespace App\Models\ChatGroup;

use App\Enums\WorkOrder\OrderEnum;
use App\Models\BaseModel;
use App\Models\Common\ConfigModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use App\Service\ChatGroup\ChatGroupFAQService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class ChatGroupFAQModel extends BaseModel
{
    protected $fillable = [
        'questionDesc',
        'questionId',
        'questionPid',
        'level',
        'description',
        'sortScore',
        'sortDateTimestamp',
        'sort',
        'answer',
        'attachment',
        'createdAt',
        'updatedAt',
        'usefulNum',
        'uselessNum',
    ];

    protected $table = 'chat_group_faq';

    /*
     * level 分级
     */

    const LEVEL_ZERO       = 1;
    const LEVEL_ZERO_SCORE = 10000;

    const LEVEL_ONE       = 2;
    const LEVEL_ONE_SCORE = 100;

    const LEVEL_TWO       = 3;
    const LEVEL_TWO_SCORE = 1;

    const LEVEL_MAPPING = [
        self::LEVEL_ZERO => '0级',
        self::LEVEL_ONE  => '1级',
        self::LEVEL_TWO  => '2级',
    ];

    const TYPE_USE_FULL = 1;
    const TYPE_USE_LESS = 2;

    const TYPE_USE_TEXT_MAPPING = [
        self::TYPE_USE_FULL => '有用',
        self::TYPE_USE_LESS => '无用',
    ];

    public function getLevelOneRel(): HasMany
    {
        return $this->hasMany(ChatGroupFAQModel::class, 'pid', 'id');
    }

    public function getLevelTwoRel(): HasMany
    {
        return $this->hasMany(ChatGroupFAQModel::class, 'pid', 'id');
    }

    public function getParentRel(): HasOne
    {
        return $this->hasOne(ChatGroupFAQModel::class, 'id', 'pid');
    }

    /**
     * 常见问题
     * @param bool $returnAns 是否需要返回答案
     * @return array
     */
    public static function faq(bool $returnAns = true): array
    {
        $data = [];

        ChatGroupFAQModel::query()
                         ->where('level', ChatGroupFAQModel::LEVEL_ZERO)
                         ->orderBy('sort')
                         ->orderByDesc('sortDateTimestamp')
                         ->with(['getLevelOneRel.getLevelTwoRel'])
                         ->get()
                         ->each(function (ChatGroupFAQModel $chatGroupFAQModel) use (&$data, $returnAns) {
                             $data[] = [
                                 'id'       => $chatGroupFAQModel->id,
                                 'desc'     => $chatGroupFAQModel->desc,
                                 'children' => $chatGroupFAQModel->getLevelOneRel->map(function ($oneRel) use (
                                     $returnAns
                                 ) {
                                     return [
                                         'id'       => $oneRel->id,
                                         'desc'     => $oneRel->desc,
                                         'children' => $oneRel->getLevelTwoRel->map(function ($twoRel) use ($returnAns
                                         ) {

                                             $ans = [];
                                             if ($returnAns) {
                                                 $ans[ChatGroupHistoryModel::TYPE_TEXT] = $twoRel->answer;

                                                 $attachment = $twoRel->attachment ? json_decode($twoRel->attachment,
                                                     true) : [];

                                                 foreach ($attachment as $file) {
                                                     if (empty($file['type'])) {
                                                         continue;
                                                     }
                                                     $ans[$file['type']] = $file['url'];
                                                 }
                                             }

                                             return array_filter([
                                                 'id'   => $twoRel->id,
                                                 'desc' => $twoRel->desc,
                                                 'ans'  => $ans,
                                             ]);
                                         })->toArray(),
                                     ];
                                 })->toArray(),
                             ];
                         });
        return $data;
    }

    /**
     * 获取问题索引
     *
     * @param string $index
     * @return Builder|Model|object|null
     */
    public static function getAnswerByIndex(string $index)
    {
        return ChatGroupFAQModel::query()
            //->select(['answer', 'attachment'])
                                ->where('indexNumber', $index)
                                ->first();
    }

    /**
     * 返回问题答案
     *
     * @param string $question
     * @param int $level
     * @return Builder|Model|object|null
     */
    public static function getAnswerByQuestion(string $question, int $level = 0)
    {
        return ChatGroupFAQModel::query()
                                ->select(['answer', 'attachment'])
                                ->where('level', $level)
                                ->where('desc', $question)
                                ->first();
    }

    /**
     * 返回问题答案
     *
     * @param int $faqId
     * @return Builder|Model|object|null
     */
    public static function getAnswerByFaqId(int $faqId)
    {
        return ChatGroupFAQModel::query()
            //->select(['answer', 'attachment'])
                                ->where('id', $faqId)
                                ->first();
    }

    /**
     * 获取子问题
     * @param int $pid
     * @return array
     */
    public static function getByPid(int $pid): array
    {
        return self::query()->with('getLevelOneRel')->where('pid', $pid)->orderBy('sort')->get()->map(function ($item) {
            return [
                'id'    => $item->id,
                'desc'  => $item->desc,
                'child' => $item->getLevelOneRel->count() > 0 ? 1 : 0,
            ];
        })->toArray();
    }

    /**
     * 根据三级indexNumber获得问题title
     * @param $indexNumber
     * @return string|null
     */
    public static function getQuestionByIndexNumber($indexNumber): ?string
    {
        $levelThreeFAQ = self::where('level', self::LEVEL_TWO)
                             ->where('indexNumber', $indexNumber)
                             ->first();

        if (!$levelThreeFAQ) {
            return '';
        }

        $levelTwoFAQ = self::where('level', self::LEVEL_ONE)
                           ->where('id', $levelThreeFAQ->pid)
                           ->first();

        if (!$levelTwoFAQ) {
            return '';
        }

        $levelOneFAQ = self::where('level', self::LEVEL_ZERO)
                           ->where('id', $levelTwoFAQ->pid)
                           ->first();

        if (!$levelOneFAQ) {
            return '';
        }

        return $levelOneFAQ->desc . '-' . $levelTwoFAQ->desc . '-' . $levelThreeFAQ->desc;
    }


    /**
     * 获得发送的工单链接
     * @return array
     */
    public static function getSendWorkOrder(): array
    {
        $sendUrl          = ConfigModel::getValueNewJson('chatGroup', 'sendWorkOrderUrl.' . config("app.env"));
        $problemUrlPrefix = $sendUrl['problem'] ?? '';
        $problem          = collect(OrderEnum::PROBLEM_FEEDBACK_TYPE_LIST)->map(function ($type) use ($problemUrlPrefix
        ) {
            $problemType   = $type['value'];
            $type["child"] = collect(enumToSelection($type["child"]))->map(function ($item) use (
                $problemType,
                $problemUrlPrefix
            ) {
                $item['href'] = $problemUrlPrefix . '?problemType=' . $problemType . '&problemValue=' . $item['value'];
                return $item;
            })->toArray();
            return $type;
        })->values()->toArray();


        $functionOpenPrefix = $sendUrl['functionOpen'] ?? '';
        $functionOpen       = [
            [
                'value' => 0,
                'key'   => '功能开通',
                'child' => collect(enumToSelection(OrderEnum::CHAT_GROUP_FUNCTION_OPEN))->map(function ($func) use (
                    $functionOpenPrefix
                ) {
                    $func['href'] = $functionOpenPrefix . '?type=' . $func['value'];
                    return $func;
                })->toArray()
            ]
        ];

        return array_values(array_merge($problem, $functionOpen));
    }

    // 通过faqId获得dialog消息体
    public static function geFaqtDialog(int $faqId): array
    {
        $faqModel = self::query()->where('id', $faqId)->first();

        return ChatGroupFAQModel::getFAQtDialogContent($faqModel->answer, $faqModel->indexNumber);
    }


    /**
     * 返回统一的标准答案
     *
     * @param string $answer
     * @param string $indexNumber
     * @param bool $isAiAnswer
     * @return array
     */
    public static function getFAQtDialogContent(string $answer, string $indexNumber, bool $isAiAnswer = false): array
    {

        return [
            'title'        => ChatGroupFAQModel::getQuestionByIndexNumber($indexNumber),
            'content'      => mb_substr($answer, 0, 30) . '...',
            'btn'          => [
                [
                    'text'   => '查看详情',
                    'type'   => 'confirm',
                    'params' => [
                        'indexNumber' => $indexNumber
                    ]
                ]
            ],
            'isAiAnswer'   => $isAiAnswer,
            'userAppraise' => [
//                [
//                    "user_id" => 5172,
//                    "solve"   => 1
//                ]
            ]
        ];
    }
}
